
$(document).ready(function(){

    //$('#friendsmenu').click();
    //make table pretty with jquery (to compensate IE's not use of :odd)
	oddEvenTableRow();
	
	// asynchronously load fb-sdk
	window.fbAsyncInit = function() {
		
    FB.init({
      appId      : '128851227267256', // App ID
      channelUrl : './libs/channel.html', // Channel File
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true  // parse XFBML
    });
    
    //check fb-status, act accordingly
    FB.getLoginStatus( getLoginStatus_simple );
    };
  
  // Load the SDK Asynchronously
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
   }(document));


});

//to make odd rows grey
function oddEvenTableRow(){
	$("#twofifty tr:nth-child(odd)").addClass("odd");	
}

//check if we have a logged in user, if not, disable clicking movies
function getLoginStatus_simple( response ){
		try{
			
			if (!response || response.error){
				safelog(response.error + " fw, 42");
			}
			else if (response.status === 'connected') {
				afterLogin();						
			} else if (response.status === 'not_authorized') {
				$("#table").click(promptForLogin);
				ifLogout();
			} else {
				$("#table").click(promptForLogin);
				ifLogout();
			}
		}
		catch(err){
			safelog(err + "fireworks, 58");
		}
}

function promptForLogin(){	
	alert("Please login first");	
}

function afterLogin(){
	$('#table').off("click");
	$('.title > span').click(checkOffMovie);
}

function ifLogout(){
	$('li#me > span.name').html("you");
	$('li#me > span.score').html("?");
}


//if user clicks on movie-titel (span), update DB via ajax
//only span: otherwise when click on link, movie is checked off.
function checkOffMovie(){
	var tablerow = $(this).parent().parent();

	if($(tablerow).hasClass("checked"))
        {
            $(tablerow).removeClass("checked");
            removeMovieForUser($(tablerow).attr("id"));
        }
        else
        {	var id = $(tablerow).attr("id");
        	if(id)
        	{	
        		safelog(id);
	        	$(tablerow).addClass("checked");
	            addMovieForUser(id);
        	}
        }

        updateScore();
}

function updateScore(){
    $("li#me > span.score").html(countMovies);
    changeLiPosition();
}

function countMovies(){
    myvar = $("tr.checked").length;
    return myvar;
}

function addMovieForUser(_id){
    var _userID = getUserIdFromHtml();
    

    var request = $.ajax({
        type: "POST",
        url: "ajax/ajaxhandler.php",
        data: {method: "addMovieForUser",userid: _userID, movieid: _id}
    });

    request.done(function(msg){
        //safelog(msg);
    });

    request.fail(function(jqXHR, textStatus){
        safelog("Request failed: " + textStatus);
    });
}

function removeMovieForUser(_id){
    var _userID = getUserIdFromHtml();

    var request = $.ajax({
        type: "POST",
        url: "ajax/ajaxhandler.php",
        data: {method: "removeMovieForUser", userid: _userID, movieid: _id}
    });

    request.done(function(msg){
        $("log").html(msg);
    });

    request.fail(function(jqXHR, textStatus){
        safelog("Request failed: " + textStatus);
    });
}

function getUserIdFromHtml(){
	return $("#loginmenu > a").attr("value");	
}

/**
 *	check if user can jump over/leap under friend in chart 
 */
function changeLiPosition(){
	//user score
	var userScore = $("li#me > span.score").html();
	
	//size li-array
	var sizeArray = $("#score > ul > li").size();
	
	//define user position in list
	var userItem = $('li#me');
	var userPos = $('#score > ul > li').index(userItem);
	
	//check if score from li-1 is lower than userscore
	if(userPos !== 0) //if user is highest placed, leave it to it then
	{
		var higherPos = parseInt(userPos) - 1;
		var higherObject =  $("#score > ul > li:eq(" + higherPos + ")");
		//higherscore
		var higherScore = $(higherObject).children("span.score").html();
		
		if(parseInt(higherScore) < parseInt(userScore))
		{
			$("li#me").exchangePositionUp(higherObject);
			//check if new user above had same score as the one we just skipped
			changeLiPosition();
		}
	}
	
	//check if score from li+1 is higher than userScore
	if(userPos !== parseInt(sizeArray) - 1 )
	{
		var lowerPos = parseInt(userPos) + 1;
		var lowerObject = $("#score > ul > li:eq(" + lowerPos + ")");
		
		//lowerscore
		var lowerScore = $(lowerObject).children("span.score").html();
		
		if(lowerScore > userScore)
		{
			$("li#me").exchangePositionDown(lowerObject);
			//check if new user under us had same score as the one we just skipped
			changeLiPosition();
		}	
		
	}
	
}
//custom jquery functions to change li-position
$.fn.exchangePositionUp = function(selector){
	var other = $(selector);
	this.before(other.clone());
	other.before(this).remove();
};
$.fn.exchangePositionDown = function(selector){
	var other = $(selector);
	this.after(other.clone());
	other.after(this).remove();
};

function onResize(){
    //may be needed for tablets, phones, ...
}
